package com.doris.lucene.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;

import com.doris.lucene.Constants;
import com.doris.lucene.LuceneSearcher;
import com.doris.lucene.Pager;
import com.doris.lucene.SearchWordStat;

/**
 * 接收用户的搜索请求
 * 
 * @author root
 *
 */
public class SearchServlet extends HttpServlet {

	private static final long serialVersionUID = 7050285078646260208L;
	/**
	 * 搜索词
	 */
	private static final String QUERY_WORD = "queryWord";
	/**
	 * 当前页
	 */
	private static final String CURRENT_PAGE = "currentPage";
	private static LuceneSearcher searcher = new LuceneSearcher();

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding(Constants.UTF8);
		Integer currentPage = Integer.valueOf(request.getParameter(CURRENT_PAGE)); // 当前分页数
		request.setAttribute(CURRENT_PAGE, currentPage);
		String queryWord = request.getParameter(QUERY_WORD); // 搜索词
		if (queryWord != null && !queryWord.isEmpty()) {
			queryWord = queryWord.trim().replaceAll("“", "\"").replaceAll("”", "\"");
			request.setAttribute(QUERY_WORD, StringEscapeUtils.escapeHtml(queryWord));
			
			Map<String, Integer> map = SearchWordStat.getSingleton().getMap();
			if (map.get(queryWord) == null) {
				map.put(queryWord, 1);
			} else {
				map.put(queryWord, map.get(queryWord) + 1);
			}
			
			Pager pager = searcher.search(queryWord, currentPage);
			request.setAttribute("results", pager.getResults());
			request.setAttribute(CURRENT_PAGE, currentPage);
			request.setAttribute("total", pager.getTotal());
			request.setAttribute("totalPages", pager.getTotalPages());
			request.getRequestDispatcher("searchResult.jsp").forward(request, response);
		} else {
			doGet(request, response);
		}
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.sendRedirect(request.getContextPath());
	}

}
